package com.keboom.show.controller;

import com.keboom.show.common.api.CommonResult;
import com.keboom.show.dto.ManagerLoginParam;
import com.keboom.show.model.SpManager;
import com.keboom.show.service.ManagerService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by keboom on 2020/9/7.
 */
@RestController
@RequestMapping("/api")
public class ManagerController {
    @Autowired
    private ManagerService managerService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public CommonResult<SpManager> register(@RequestBody SpManager Manager) {
        SpManager manager = managerService.register(Manager);
        if (manager == null) {
            CommonResult.failed();
        }
        return CommonResult.success(manager);
    }

    @ApiOperation(value = "登录以后返回token")
    @PostMapping("/login")
    public CommonResult login(@RequestBody ManagerLoginParam managerLoginParam) {
        String token = managerService.login(managerLoginParam.getUsername(), managerLoginParam.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        SpManager manager = managerService.getManagerByUsername(managerLoginParam.getUsername());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("id", String.valueOf(manager.getMgId()));
        tokenMap.put("rid", String.valueOf(manager.getRoleId()));
        tokenMap.put("username", manager.getMgName());
        tokenMap.put("mobile", manager.getMgMobile());
        tokenMap.put("email", manager.getMgEmail());
        return CommonResult.success(tokenMap);
    }
}
